<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">

                <el-form-item label="时间范围">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')"
                        :picker-options="pickerOptions" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>

                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <div class="flex_between">
                <div>{{ str }}成功续订</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport">{{ $t('table.export') }}</el-button>
            </div>
            <div class="police-count1" ref="chart1"></div>
            <div class="flex_between">
                <div>{{ str }}成功退款</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport2">{{ $t('table.export') }}</el-button>
            </div>
            <div class="police-count2" ref="chart2"></div>
            <div class="flex_between">
                <div>{{ str }}转正率</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport3">{{ $t('table.export') }}</el-button>
            </div>
            <div class="police-count3" ref="chart3"></div>
            <div class="flex_between">
                <div>{{ str }}直接购买</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport4">{{ $t('table.export') }}</el-button>
            </div>

            <div class="police-count4" ref="chart4"></div>

            <div class="flex_between">
                <div>{{ str }}试用人数</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport5">{{ $t('table.export') }}</el-button>
            </div>
            <div class="police-count5" ref="chart5"></div>

            <div class="flex_between">
                <div>{{ str }}新增人数</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport6">{{ $t('table.export') }}</el-button>
            </div>
            <div class="police-count6" ref="chart6"></div>

            <div class="flex_between">
                <div>{{ str }}试用率</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport7">{{ $t('table.export') }}</el-button>
            </div>
            <div class="police-count7" ref="chart7"></div>
            <div class="flex_between">
                <div>{{ str }}新增用户订阅转化率-均值:({{ conversionRateMean }}%)</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport8">{{ $t('table.export') }}</el-button>
            </div>
            <div class="police-count8" ref="chart8"></div>
        </el-card>
    </div>
</template>
<script>
import { calculateDailySuccessfulPayments, calculateDailySuccessfulRefunds, calculateConversionRate, calculateDailyDirectPurchases, calculateInitialBuysWithFreeTrial, getWeeklyRenewalRatesByPk, calculateDailyNewUsers, calculateTrialConversionRate, newUserSubscriptionRateThreeDaysLater } from "@/api/subscription";
import { getLanguage, gptTranslate } from "@/api/appComment";
import pk from "@/utils/pk";
import * as XLSX from "xlsx";
export default {
    name: "subscription",
    data() {
        return {
            languageContent: '',
            goalLanguage: "zh_CN",
            languageList: [],
            translateLoading: false,
            pkList: [],

            queryParams: {
                dateRange: {
                    start: '',
                    end: ''
                },
                pk: "",
            },
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                comment_type: "",
            },
            search: "",
            rules: {
                comment_type: [
                    { required: true, message: "请输入类型", trigger: "blur" },
                ],
            },
            value1: "",
            chartContainer1: null,
            option1: {},
            chartData: [],
            chartContainer2: null,
            option2: {},
            chartData2: [],
            chartContainer3: null,
            option3: {},
            chartData3: [],
            chartContainer4: null,
            option4: {},
            chartData4: [],
            chartContainer5: null,
            option5: {},
            chartData5: [],
            chartContainer6: null,
            option6: {},
            chartData6: [],
            chartContainer7: null,
            option7: {},
            chartData7: [],
            chartContainer8: null,
            option8: {},
            chartData8: [],
            isLoading1: true,
            chart1: null,
            chart2: null,
            chart3: null,
            chart4: null,
            chart5: null,
            chart6: null,
            chart7: null,
            chart8: null,
            loadingOption: {
                text: '',
                color: '#409eff',
                maskColor: 'rgba(255, 255, 255, 0.8)',
                zlevel: 0
            },
            pk: '',
            pickerOptions: {

            },
            invalidDateRange: false,
            str: '近30天',
            conversionRateMean: 0

        };
    },
    created() {

    },

    mounted() {
        // this.pickerOptions = {
        //     onPick: ({ maxDate, minDate }) => {
        //         if (minDate && maxDate) {
        //             // 验证选择的日期范围
        //             const oneMonthLater = new Date(minDate);
        //             oneMonthLater.setMonth(oneMonthLater.getMonth() + 1);

        //             if (maxDate > oneMonthLater) {
        //                 // 如果超过一月范围
        //                 this.$nextTick(() => {
        //                     alert('选择的日期范围不能超过一个月');
        //                     this.value1 = []
        //                     // 立即重置 maxDate 以取消选择
        //                     this.invalidDateRange = true; // 设置标志位为 true
        //                 });
        //             } else {
        //                 this.invalidDateRange = false; // 设置标志位为 false
        //             }
        //         }
        //     }
        // };
        const { pk } = this.$route.query;
        this.queryParams.pk = pk
        this.pk = pk
        this.getStatistics(pk);
        this.getStatistics2(pk);
        this.getStatistics3(pk);
        this.getStatistics4(pk);
        this.getStatistics5(pk);
        this.getStatistics6(pk);
        this.getStatistics7(pk);
        this.getStatistics8(pk);
    },
    methods: {

        formatDate(date) {
            const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
            return new Date(date).toLocaleDateString('zh-CN', options);
        },
        async getStatistics(pk) {
            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                    pk: pk
                };

            }


            this.chart1 = this.$echarts.init(this.$refs.chart1);
            // 显示加载动画
            this.chart1.showLoading(this.loadingOption);
            // console.log(this.queryParams)
            let { data } = await calculateDailySuccessfulPayments(this.queryParams);
            this.chartData = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.count);

            this.option1 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13,
                        interval: 'auto' // 自动设置标签显示间隔
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13,
                        interval: 'auto' // 自动设置标签显示间隔。对于 y 轴，可以不设置，因为默认已经是自动的。
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };

            setTimeout(() => {
                this.initChart1();
                this.chart1.hideLoading();

            })
        },
        async getStatistics2(pk) {

            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                    pk: pk
                };


            }

            this.chart2 = this.$echarts.init(this.$refs.chart2);
            // 显示加载动画
            this.chart2.showLoading(this.loadingOption);
            // console.log(this.queryParams)
            let { data } = await calculateDailySuccessfulRefunds(this.queryParams);
            this.chartData2 = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.count);

            this.option2 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart2();
                this.chart2.hideLoading();

            })
        },
        async getStatistics3(pk) {
            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                    pk: pk
                };


            }
            this.chart3 = this.$echarts.init(this.$refs.chart3);
            // 显示加载动画
            this.chart3.showLoading(this.loadingOption);
            let { data } = await calculateConversionRate(this.queryParams);
            console.log(data, 'data')
            if (pk == 'com.seamobitech.UniversalTVRemoteControl') {
                data = data.filter(item => item.date !== "11-06" && item.date !== "11-03");
            }
            this.chartData3 = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.conversionRate);
            const initialCounts = data.map(item => item.initialCount);
            const renewalCounts = data.map(item => item.renewalCount);

            this.option3 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%' // 显示百分号
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                    日期: ${dates[index]}<br/>
                    转正率: ${counts[index]}%<br/>
                    试用人数: ${initialCounts[index]}<br/>
                    续费人数: ${renewalCounts[index]}
                `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart3();
                this.chart3.hideLoading();

            })
        },
        async getStatistics4(pk) {
            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                    pk: pk
                };

            }
            this.chart4 = this.$echarts.init(this.$refs.chart4);
            // 显示加载动画
            this.chart4.showLoading(this.loadingOption);
            // console.log(this.queryParams)
            let { data } = await calculateDailyDirectPurchases(this.queryParams);
            this.chartData4 = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.count);

            this.option4 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };

            setTimeout(() => {
                this.initChart4();
                this.chart4.hideLoading();

            })
        },
        async getStatistics5(pk) {
            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                    pk: pk
                };

            }


            this.chart5 = this.$echarts.init(this.$refs.chart5);
            // 显示加载动画
            this.chart5.showLoading(this.loadingOption);
            // console.log(this.queryParams)
            let { data } = await calculateInitialBuysWithFreeTrial(this.queryParams);
            this.chartData5 = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.count);

            this.option5 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };

            setTimeout(() => {
                this.initChart5();
                this.chart5.hideLoading();

            })
        },
        async getStatistics6(pk) {
            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                    pk: pk
                };

            }


            this.chart6 = this.$echarts.init(this.$refs.chart6);
            // 显示加载动画
            this.chart6.showLoading(this.loadingOption);
            // console.log(this.queryParams)
            let { data } = await calculateDailyNewUsers(this.queryParams);
            this.chartData6 = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.base_date);
            const counts = data.map(item => item.daily_new_count);

            this.option6 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };

            setTimeout(() => {
                this.initChart6();
                this.chart6.hideLoading();

            })
        },
        async getStatistics7(pk) {
            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                    pk: pk
                };


            }
            this.chart7 = this.$echarts.init(this.$refs.chart7);
            // 显示加载动画
            this.chart7.showLoading(this.loadingOption);
            let { data } = await calculateTrialConversionRate(this.queryParams);

            this.chartData7 = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.conversionRate);
            const trialCount = data.map(item => item.trialCount);
            const newCount = data.map(item => item.newCount);

            this.option7 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%' // 显示百分号
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                    日期: ${dates[index]}<br/>
                    试用率: ${counts[index]}%<br/>
                    试用人数: ${trialCount[index]}<br/>
                    新增人数: ${newCount[index]}
                `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart7();
                this.chart7.hideLoading();

            })
        },
        async getStatistics8(pk) {
            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                    pk: pk
                };


            }
            this.chart8 = this.$echarts.init(this.$refs.chart8);
            // 显示加载动画
            this.chart8.showLoading(this.loadingOption);
            let { data } = await newUserSubscriptionRateThreeDaysLater(this.queryParams);
            // 过滤出 newSubs3Days 有值的记录
            data = data.filter(item => item.newSubs3Days > 0);

            // 计算 conversion_rate 的均值
            const conversionRates = data.map(item => parseFloat(item.conversion_rate));
            this.conversionRateMean = conversionRates.length > 0
                ? (conversionRates.reduce((sum, rate) => sum + rate, 0) / conversionRates.length).toFixed(2)
                : 0;
            this.chartData8 = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.conversion_rate);
            const dailyNewCount = data.map(item => item.daily_new_count);
            const newSubs3Days = data.map(item => item.newSubs3Days);
            const dailyTrialCount = data.map(item => item.daily_trial_count);

            this.option8 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%' // 显示百分号
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                    日期: ${dates[index]}<br/>
                    转化率: ${counts[index]}%<br/>
                    新增人数: ${dailyNewCount[index]}<br/>
                    试用人数: ${dailyTrialCount[index]}<br/>
                    实际订阅人数: ${newSubs3Days[index]}
                `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart8();
                this.chart8.hideLoading();

            })
        },
        timeChange() {
            if (this.invalidDateRange) return; // 如果标志位为 true，则退出
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.str = this.value1[0] + '-' + this.value1[1]

            this.getStatistics(this.pk);
            this.getStatistics2(this.pk);
            this.getStatistics3(this.pk);
            this.getStatistics4(this.pk);
            this.getStatistics5(this.pk);
            this.getStatistics6(this.pk);
            this.getStatistics7(this.pk);
            this.getStatistics8(this.pk);
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },

        resetQuery() {
            this.queryParams.state = null;
            this.queryParams.package_name = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.str = '近30天'

            this.getStatistics(this.pk);
            this.getStatistics2(this.pk);
            this.getStatistics3(this.pk);
            this.getStatistics4(this.pk);
            this.getStatistics5(this.pk);
            this.getStatistics6(this.pk);
            this.getStatistics7(this.pk);
            this.getStatistics8(this.pk);
        },
        async handleExport() {
            // 打开 loading，防止重复点击
            this.loading = true;

            // 获取每日成功支付数据
            let { data } = await calculateDailySuccessfulPayments(this.queryParams);

            // 定义导出字段及表头中文
            const headers = {
                date: '日期',
                count: '续订人数'
            };

            // 字段转为表头（key 替换成中文），只保留 headers 定义的字段
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in headers) {
                    newItem[headers[key]] = item[key] !== undefined ? item[key] : '';
                }
                return newItem;
            });

            // 用 SheetJS 的 json_to_sheet + sheet_to_csv 导出 csv 字符串
            // { skipHeader: false } 保证首行是中文表头
            // 可以加 \uFEFF 作为 UTF-8 BOM 头，防止 Excel 中文乱码
            let csv = XLSX.utils.sheet_to_csv(
                XLSX.utils.json_to_sheet(transformedData),
                { FS: ",", RS: "\n", skipHeader: false }
            );
            // 如果需要兼容 Excel 中文表头，加 BOM
            csv = "\uFEFF" + csv;

            // 构建 Blob
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });

            // 创建 a 标签并自动下载
            const link = document.createElement("a");
            const url = URL.createObjectURL(blob);
            link.href = url;
            link.download = "每日成功支付统计.csv";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);

            // 关闭 loading
            this.loading = false;
        },
        async downloadCSV(data, headers, filename) {
            // 转换数据: 只保留 headers 定义字段且 key 替换成中文
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in headers) {
                    newItem[headers[key]] = item[key] !== undefined ? item[key] : '';
                }
                return newItem;
            });

            // 用 SheetJS json_to_sheet 转 sheet, 然后 sheet_to_csv 得到 CSV 字符串
            let csv = XLSX.utils.sheet_to_csv(
                XLSX.utils.json_to_sheet(transformedData),
                { FS: ",", RS: "\n", skipHeader: false }
            );
            // 为防止 Excel 打开中文乱码，建议加 BOM
            csv = "\uFEFF" + csv;

            // 构造 Blob
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });

            // 创建下载链接并自动下载
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);
        },

        async handleExport2() {
            this.loading = true;
            let { data } = await calculateDailySuccessfulRefunds(this.queryParams);
            const headers = { date: '日期', count: '退款人数' };
            await this.downloadCSV(data, headers, '每日退款人数统计.csv');
            this.loading = false;
        },
        async handleExport3() {
            this.loading = true;
            let { data } = await calculateConversionRate(this.queryParams);
            const headers = {
                date: '日期',
                initialCount: '试用',
                renewalCount: '续费人数',
                conversionRate: '转正率'
            };
            await this.downloadCSV(data, headers, '转正率统计.csv');
            this.loading = false;
        },
        async handleExport4() {
            this.loading = true;
            let { data } = await calculateDailyDirectPurchases(this.queryParams);
            const headers = { date: '日期', count: '直接购买人数' };
            await this.downloadCSV(data, headers, '每日直接购买统计.csv');
            this.loading = false;
        },
        async handleExport5() {
            this.loading = true;
            let { data } = await calculateInitialBuysWithFreeTrial(this.queryParams);
            const headers = { date: '日期', count: '试用人数' };
            await this.downloadCSV(data, headers, '每日试用人数统计.csv');
            this.loading = false;
        },
        async handleExport6() {
            this.loading = true;
            let { data } = await calculateDailyNewUsers(this.queryParams);
            const headers = { base_date: '日期', daily_new_count: '新增人数' };
            await this.downloadCSV(data, headers, '每日新增人数统计.csv');
            this.loading = false;
        },
        async handleExport7() {
            this.loading = true;
            let { data } = await calculateTrialConversionRate(this.queryParams);
            const headers = {
                date: '日期',
                newCount: '新增人数',
                trialCount: '试用人数',
                conversionRate: '试用率',
            };
            await this.downloadCSV(data, headers, '每日试用率统计.csv');
            this.loading = false;
        },
        async handleExport8() {
            this.loading = true;
            let { data } = await newUserSubscriptionRateThreeDaysLater(this.queryParams);
            const headers = {
                date: '日期',
                daily_new_count: '新增人数',
                daily_trial_count: '试用人数',
                newSubs3Days: '实际订阅人数',
                conversion_rate: '订阅率',
            };

            // 处理数据，并追加一行均值
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in headers) {
                    newItem[headers[key]] = item[key] !== undefined ? item[key] : '';
                }
                return newItem;
            });
            // 如有均值，作为特殊行加入
            transformedData.push({ '均值': this.conversionRateMean });

            let csv = XLSX.utils.sheet_to_csv(
                XLSX.utils.json_to_sheet(transformedData),
                { FS: ",", RS: "\n", skipHeader: false }
            );
            csv = "\uFEFF" + csv;
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = '每日新用户三天后订阅率统计.csv';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);

            this.loading = false;
        },
        initChart1() {
            this.chartContainer1 = this.$echarts.init(document.querySelector('.police-count1'))
            this.chartContainer1.setOption(this.option1)
        },
        initChart2() {
            this.chartContainer2 = this.$echarts.init(document.querySelector('.police-count2'))
            this.chartContainer2.setOption(this.option2)
        },
        initChart3() {
            this.chartContainer3 = this.$echarts.init(document.querySelector('.police-count3'))
            this.chartContainer3.setOption(this.option3)
        },
        initChart4() {
            this.chartContainer4 = this.$echarts.init(document.querySelector('.police-count4'))
            this.chartContainer4.setOption(this.option4)
        },
        initChart5() {
            this.chartContainer5 = this.$echarts.init(document.querySelector('.police-count5'))
            this.chartContainer5.setOption(this.option5)
        },
        initChart6() {
            this.chartContainer6 = this.$echarts.init(document.querySelector('.police-count6'))
            this.chartContainer6.setOption(this.option6)
        },
        initChart7() {
            this.chartContainer7 = this.$echarts.init(document.querySelector('.police-count7'))
            this.chartContainer7.setOption(this.option7)
        },
        initChart8() {
            this.chartContainer8 = this.$echarts.init(document.querySelector('.police-count8'))
            this.chartContainer8.setOption(this.option8)
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-image {
    margin-right: 8px;
    border-radius: 4px;
}

.statistics-container {
    display: flex;
    flex-wrap: wrap;
    /* 自动换行 */
    gap: 10px;
    /* 数据块之间的间距 */
    padding: 10px;
    border: 1px solid #ddd;
    margin-bottom: 20px;
    font-size: 14px;
}

.item {
    background-color: #f9f9f9;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    display: inline-block;
    /* 使得每个元素成为一块 */
    white-space: nowrap;
    /* 防止单个元素中的文本换行 */
}

.police-count1,
.police-count2,
.police-count3,
.police-count4,
.police-count5,
.police-count6,
.police-count7,
.police-count8 {
    width: 100%;
    min-width: 1000px;
    height: 350px;
    color: #000;
}


.loading .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.loading-spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg) !important;
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>